import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
import java.util.regex.Pattern;

/**
 * Created by VectorHo on 16/6/13.
 * <p/>
 * 自动去Kong注册成为上游Api服务.  ---启动springbootApplication时运行
 */
public class GetIp2 {

    private static final String LOCALHOST = "127.0.0.1";
    private static final String ANYHOST = "0.0.0.0";
    private static final Pattern IP_PATTERN = Pattern.compile("\\d{1,3}(\\.\\d{1,3}){3,5}$");

    /**
     * 遍历本地网卡，返回第一个合理的IP。
     *
     * @return 本地网卡IP
     */
    private static InetAddress getLocalAddress0() throws Exception {
        InetAddress localAddress = null;
        try {
            localAddress = InetAddress.getLocalHost();
            if (isValidAddress(localAddress)) {
                return localAddress;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println("localAddress=" + localAddress);
        Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
        if (interfaces != null) {
            while (interfaces.hasMoreElements()) {
                NetworkInterface network = interfaces.nextElement();
                Enumeration<InetAddress> addresses = network.getInetAddresses();
                if (addresses != null) {
                    while (addresses.hasMoreElements()) {
                        InetAddress address = addresses.nextElement();
                        if (isValidAddress(address)) {
                            return address;
                        } else {
                            System.out.println("pass " + address);
                        }
                    }
                }
            }
        }
        return localAddress;
    }

    private static boolean isValidAddress(InetAddress address) {
        //isLoopbackAddress:127.*,isSiteLocalAddress:局域网ip,isLinkLocalAddress:169.254.*,isMulticastAddress:224.0.0.0 ~ 239.255.255.255
        if (address != null) {
            String hostIp = address.getHostAddress();
            if (hostIp.startsWith("10.")) {
                return true;
            }
        }
        if (address == null
                || address.isLoopbackAddress()
                || address.isSiteLocalAddress()
                || address.isLinkLocalAddress()
                || address.isMulticastAddress()
                || isSpecialIp(address.getHostAddress())
                ) {
            return false;
        }
        String name = address.getHostAddress();
        return (name != null && !ANYHOST.equals(name) && !LOCALHOST.equals(name) && IP_PATTERN.matcher(name).matches());
    }

    private static boolean isSpecialIp(String ip) {
        if (ip.contains(":")) return true;
        if (ip.equals("255.255.255.255")) return true;
        return false;
    }

    public static void main(String[] args) throws Exception {
        InetAddress addr = getLocalAddress0();
        System.out.println("select: " + addr);
    }
}
